<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.1.2">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.1.2">


  <link rel="mask-icon" href="/images/logo.svg?v=7.1.2" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '7.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="基于swift5.1写的">
<meta name="keywords" content="iOS,Swift">
<meta property="og:type" content="article">
<meta property="og:title" content="Swift">
<meta property="og:url" content="https://rencheng.cc/2019/07/20/ios/swift/基础语法/index.html">
<meta property="og:site_name" content="PHOENIX&#39;s Blog">
<meta property="og:description" content="基于swift5.1写的">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://object.renchengqi.com/blog/m7u8l.png">
<meta property="og:image" content="https://object.renchengqi.com/blog/g2c1n.png">
<meta property="og:image" content="https://object.renchengqi.com/blog/i1pnj.png">
<meta property="og:updated_time" content="2019-07-20T02:51:47.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Swift">
<meta name="twitter:description" content="基于swift5.1写的">
<meta name="twitter:image" content="https://object.renchengqi.com/blog/m7u8l.png">



  <link rel="alternate" href="/atom.xml" title="PHOENIX's Blog" type="application/atom+xml">



  
  
  <link rel="canonical" href="https://rencheng.cc/2019/07/20/ios/swift/基础语法/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Swift | PHOENIX's Blog</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">PHOENIX's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">Enjoy the journey of life</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://rencheng.cc/2019/07/20/ios/swift/基础语法/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="任成">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="PHOENIX's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Swift

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-07-20 10:51:47" itemprop="dateCreated datePublished" datetime="2019-07-20T10:51:47+08:00">2019-07-20</time>
            

            
          </span>

          

          
            
            
          

          
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                <span title="本文字数">6.4k</span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>基于swift5.1写的<br><a id="more"></a></p>
<h2 id="基础语法"><a href="#基础语法" class="headerlink" title="基础语法"></a>基础语法</h2><h3 id="输出"><a href="#输出" class="headerlink" title="输出"></a>输出</h3><figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">print(<span class="string">"Hello World"</span>)</span><br></pre></td></tr></table></figure>
<ul>
<li>不用编写main函数，Swift将全局范围内的首句可执行代码作为程序入口</li>
<li>一句代码尾部可以省略分号(;)，多句代码写到同一行时必须用分号(;)隔开 </li>
<li><p>用<code>var</code>定义变量，<code>let</code>定义常量，编译器能自动推断出变量\常量的类型</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a = <span class="number">10</span></span><br><span class="line"><span class="keyword">let</span> b = <span class="number">20</span></span><br><span class="line"><span class="keyword">var</span> <span class="built_in">c</span> = a + b</span><br><span class="line"><span class="built_in">c</span> += <span class="number">30</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>Playground可以快速预览代码效果，是学习语法的好帮手 </p>
</li>
<li><code>Command + Shift + Enter</code>:运行整个Playground</li>
<li><code>Shift + Enter</code>:运行截止到某一行代码</li>
</ul>
<h3 id="注释"><a href="#注释" class="headerlink" title="注释"></a>注释</h3><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 单行注释</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> 多行注释</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> 1</span></span><br><span class="line"><span class="comment"> <span class="comment">/* 多行注释嵌套 */</span></span></span><br><span class="line"><span class="comment"> 2</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>
<h3 id="常量"><a href="#常量" class="headerlink" title="常量"></a>常量</h3><ul>
<li>只能赋值1次</li>
<li>它的值不要求在编译时期确定，但使用之前必须赋值1次</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> age1 = <span class="number">10</span></span><br><span class="line"><span class="keyword">let</span> age2: <span class="type">Int</span></span><br><span class="line">age2 = <span class="number">20</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">getAge</span><span class="params">()</span></span> -&gt; <span class="type">Int</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">30</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> age3 = getAge()</span><br></pre></td></tr></table></figure>
<ul>
<li>常量、变量在初始化之前，都不能使用</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> age: <span class="type">Int</span></span><br><span class="line"><span class="keyword">var</span> height: <span class="type">Int</span></span><br><span class="line"><span class="built_in">print</span>(age)</span><br><span class="line"><span class="built_in">print</span>(height)</span><br></pre></td></tr></table></figure>
<ul>
<li>下面代码是错误的</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> age</span><br><span class="line">age = <span class="number">20</span></span><br></pre></td></tr></table></figure>
<h3 id="标识符"><a href="#标识符" class="headerlink" title="标识符"></a>标识符</h3><ul>
<li>标识符(比如常量名、变量名、函数名)几乎可以使用任何字符</li>
<li>标识符不能以数字开头，不能包含空白字符、制表符、箭头等特殊字符</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> 🐂🍺<span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"666"</span>)</span><br><span class="line">&#125;</span><br><span class="line">🐂🍺()</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> 👽 = <span class="string">"ET"</span></span><br><span class="line"><span class="keyword">var</span> 🥛 = <span class="string">"milk"</span></span><br></pre></td></tr></table></figure>
<h3 id="常用数据类型"><a href="#常用数据类型" class="headerlink" title="常用数据类型"></a>常用数据类型</h3><p><img src="https://object.renchengqi.com/blog/m7u8l.png" alt></p>
<ul>
<li>整数类型:Int8、Int16、Int32、Int64、UInt8、UInt16、UInt32、UInt64 </li>
<li>在32bit平台，Int等价于Int32，Int等价于Int64</li>
<li>整数的最值:UInt8.max、Int16.min</li>
<li><p>一般情况下，都是直接使用Int即可</p>
</li>
<li><p>浮点类型:Float，32位，精度只有6位;Double，64位，精度至少15位</p>
</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> letFloat: <span class="type">Float</span> = <span class="number">30.0</span></span><br><span class="line"><span class="keyword">let</span> letDouble = <span class="number">30.0</span></span><br></pre></td></tr></table></figure>
<h3 id="字面量"><a href="#字面量" class="headerlink" title="字面量"></a>字面量</h3><p><strong>布尔</strong><br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> bool = <span class="literal">true</span> <span class="comment">// 取反是false</span></span><br></pre></td></tr></table></figure></p>
<p><strong>字符串</strong><br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> string = <span class="string">"飞翔"</span></span><br></pre></td></tr></table></figure></p>
<p><strong>字符(可存储ASCII字符、Unicode字符)</strong><br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> character: <span class="type">Character</span> = <span class="string">"🐶"</span></span><br></pre></td></tr></table></figure></p>
<p><strong>整数</strong><br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> intDecimal = <span class="number">15</span> <span class="comment">//十进制</span></span><br><span class="line"><span class="keyword">let</span> intBinary = <span class="number">0b10001</span> <span class="comment">// 二进制</span></span><br><span class="line"><span class="keyword">let</span> intOctal = <span class="number">0o21</span> <span class="comment">// 八进制</span></span><br><span class="line"><span class="keyword">let</span> intHexadecimal = <span class="number">0x11</span> <span class="comment">// 十六进制</span></span><br></pre></td></tr></table></figure></p>
<blockquote>
<p> 整数和浮点数可以添加额外的零或者添加下划线来增强可读性 <code>p100_0000</code>、 <code>1_000_000.000_000_1</code>、 <code>000123.456</code></p>
</blockquote>
<p><strong>浮点数</strong><br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> doubleDecimal = <span class="number">15.0</span> <span class="comment">//十进制, 等价于1.25e2,0.0125等价于1.25e-2</span></span><br><span class="line"><span class="keyword">let</span> doubleHexadecimal1 = 0xFp2 <span class="comment">// 十六进制, 意味着25×2^2，相当于十进制的60</span></span><br><span class="line"><span class="keyword">let</span> doubleHexadecimal2 = 0xFp-<span class="number">2</span> <span class="comment">// 十六进制, 意味着25×2^-2，相当于十进制的3.75</span></span><br></pre></td></tr></table></figure></p>
<p><strong>数组</strong><br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> array = [<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">7</span>, <span class="number">9</span>]</span><br></pre></td></tr></table></figure></p>
<p><strong>字典</strong><br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> dictionary = [<span class="string">"age"</span>: <span class="number">18</span>, <span class="string">"height"</span>: <span class="number">168</span>, <span class="string">"weight"</span>: <span class="number">120</span>]</span><br></pre></td></tr></table></figure></p>
<h3 id="类型转换"><a href="#类型转换" class="headerlink" title="类型转换"></a>类型转换</h3><p><strong>整数转换</strong><br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> int1: <span class="type">UInt16</span> = <span class="number">2_000</span></span><br><span class="line"><span class="keyword">let</span> int2: <span class="type">UInt8</span> = <span class="number">1</span></span><br><span class="line"><span class="keyword">let</span> int3 = int1 + <span class="type">UInt16</span>(int2)</span><br></pre></td></tr></table></figure></p>
<p><strong>整数、浮点数转换</strong><br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> int = <span class="number">3</span></span><br><span class="line"><span class="keyword">let</span> double = <span class="number">0.14</span></span><br><span class="line"><span class="keyword">let</span> pi = <span class="type">Double</span>(int) + double</span><br><span class="line"><span class="keyword">let</span> intPi = <span class="type">Int</span>(pi)</span><br></pre></td></tr></table></figure></p>
<p><strong>字面量相加</strong><br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 字面量可以直接相加，欣慰数字字面量本身没有明确类型</span></span><br><span class="line"><span class="keyword">let</span> result = <span class="number">3</span> + <span class="number">0.14</span></span><br></pre></td></tr></table></figure></p>
<h3 id="元组"><a href="#元组" class="headerlink" title="元组"></a>元组</h3><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> http404Error = (<span class="number">404</span>, <span class="string">"Not Found"</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">"The status code is \(http404Error.0)"</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> (statusCode, statusMessage) = http404Error</span><br><span class="line"><span class="built_in">print</span>(<span class="string">"The status code is \(statusCode)"</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> (justTheStatusCode, <span class="number">_</span>) = http404Error</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> http200Error = (statusCode: <span class="number">200</span>, description: <span class="string">"OK"</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">"The status code is \(http200Error.statusCode)"</span>)</span><br></pre></td></tr></table></figure>
<h2 id="流程控制"><a href="#流程控制" class="headerlink" title="流程控制"></a>流程控制</h2><h3 id="if-else"><a href="#if-else" class="headerlink" title="if-else"></a>if-else</h3><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> age = <span class="number">4</span></span><br><span class="line"><span class="keyword">if</span> age &gt;= <span class="number">22</span> &#123;</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"Get married"</span>)</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> age &gt;= <span class="number">18</span> &#123;</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"Being a adult"</span>)</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> age &gt;= <span class="number">7</span> &#123;</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"Go to school"</span>)</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"Just a child"</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>if后面的条件可以省略小括号</li>
<li>条件后边的大括号不可以省略</li>
<li>if后边的条件智能是Bool类型</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 错误代码</span></span><br><span class="line"><span class="keyword">let</span> age = <span class="number">1</span></span><br><span class="line"><span class="keyword">if</span> age &#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="while"><a href="#while" class="headerlink" title="while"></a>while</h3><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> num = <span class="number">5</span></span><br><span class="line"><span class="keyword">where</span> num &gt; <span class="number">5</span> &#123;</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"num is \(num)"</span>)</span><br><span class="line">    num -= <span class="number">1</span></span><br><span class="line">&#125; <span class="comment">//打印了5次</span></span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> num = -<span class="number">1</span></span><br><span class="line"><span class="keyword">repeat</span> &#123;</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"num is \(num)"</span>)</span><br><span class="line">    num -= <span class="number">1</span></span><br><span class="line">&#125; <span class="keyword">while</span> num &gt; <span class="number">0</span> <span class="comment">//打印了1次</span></span><br></pre></td></tr></table></figure>
<ul>
<li>repeat-while 相当于C语言的do-while</li>
<li>这里不用num—，是因为从Swift3开始，去除了自增（++），自减（—）运算符</li>
</ul>
<h3 id="for"><a href="#for" class="headerlink" title="for"></a>for</h3><h4 id="闭区间运算符：a…b-a-lt-取值-lt-b"><a href="#闭区间运算符：a…b-a-lt-取值-lt-b" class="headerlink" title="闭区间运算符：a…b, a &lt;= 取值 &lt;= b"></a>闭区间运算符：a…b, a &lt;= 取值 &lt;= b</h4><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> names = [<span class="string">"Anna"</span>, <span class="string">"Alex"</span>, <span class="string">"Brian"</span>, <span class="string">"Jack"</span>]</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="number">0</span>...<span class="number">3</span> &#123;</span><br><span class="line">    <span class="built_in">print</span>(names[i])</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// Anna, Alex, Brian, Jack</span></span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> names = [<span class="string">"Anna"</span>, <span class="string">"Alex"</span>, <span class="string">"Brian"</span>, <span class="string">"Jack"</span>]</span><br><span class="line"><span class="keyword">let</span> range = <span class="number">1</span>...<span class="number">3</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range &#123;</span><br><span class="line">    <span class="built_in">print</span>(names[i])</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// Alex, Brian, Jack</span></span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> names = [<span class="string">"Anna"</span>, <span class="string">"Alex"</span>, <span class="string">"Brian"</span>, <span class="string">"Jack"</span>]</span><br><span class="line"><span class="keyword">let</span> a = <span class="number">1</span></span><br><span class="line"><span class="keyword">let</span> b = <span class="number">2</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> a...b &#123;</span><br><span class="line">    <span class="built_in">print</span>(name[i])</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// Alex, Brian</span></span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// i默认是let, 如果有需要可以声明为var</span></span><br><span class="line"><span class="keyword">for</span> <span class="keyword">var</span> i <span class="keyword">in</span> <span class="number">1</span>...<span class="number">3</span> &#123;</span><br><span class="line">    i += <span class="number">5</span></span><br><span class="line">    <span class="built_in">print</span>(i)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 6 7 8</span></span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> <span class="number">_</span> i <span class="keyword">in</span> <span class="number">1</span>...<span class="number">3</span> &#123;</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"for"</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 打印了三次</span></span><br></pre></td></tr></table></figure>
<h4 id="半开区间运算符：a-lt-b-a-lt-取值-lt-b"><a href="#半开区间运算符：a-lt-b-a-lt-取值-lt-b" class="headerlink" title="半开区间运算符：a..&lt;b, a &lt;= 取值 &lt; b"></a>半开区间运算符：a..&lt;b, a &lt;= 取值 &lt; b</h4><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="number">1</span>..&lt;<span class="number">5</span> &#123;</span><br><span class="line">    <span class="built_in">print</span>(i)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 1 2 3 4</span></span><br></pre></td></tr></table></figure>
<h4 id="区间运算符用在数组上"><a href="#区间运算符用在数组上" class="headerlink" title="区间运算符用在数组上"></a>区间运算符用在数组上</h4><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> names = [<span class="string">"Anna"</span>, <span class="string">"Alex"</span>, <span class="string">"Brian"</span>, <span class="string">"Jack"</span>]</span><br><span class="line"><span class="keyword">for</span> name <span class="keyword">in</span> names[<span class="number">0</span>...<span class="number">3</span>] &#123;</span><br><span class="line">    <span class="built_in">print</span>(name)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// Anna, Alex, Brian, Jack</span></span><br></pre></td></tr></table></figure>
<p><strong>单侧区间</strong><br>让区间朝着一个方向尽可能的远<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> names = [<span class="string">"Anna"</span>, <span class="string">"Alex"</span>, <span class="string">"Brian"</span>, <span class="string">"Jack"</span>]</span><br><span class="line"><span class="keyword">for</span> name <span class="keyword">in</span> names[<span class="number">2</span>...] &#123;</span><br><span class="line">    <span class="built_in">print</span>(name)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// Brian, Jack</span></span><br></pre></td></tr></table></figure></p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> name <span class="keyword">in</span> names[...<span class="number">2</span>] &#123;</span><br><span class="line">    <span class="built_in">print</span>(name)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// Anna, Alex, Brian</span></span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> name <span class="keyword">in</span> names[..&lt;<span class="number">2</span>] &#123;</span><br><span class="line">    <span class="built_in">print</span>(name)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// Anna, Alex</span></span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> range = ...<span class="number">5</span></span><br><span class="line">range.<span class="built_in">contains</span>(<span class="number">7</span>) <span class="comment">// false</span></span><br><span class="line">range.<span class="built_in">contains</span>(<span class="number">4</span>) <span class="comment">// true</span></span><br><span class="line">range.<span class="built_in">contains</span>(<span class="number">7</span>-<span class="number">3</span>) <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<h4 id="区间类型"><a href="#区间类型" class="headerlink" title="区间类型"></a>区间类型</h4><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> range1: <span class="type">ClosedRange</span>&lt;<span class="type">Int</span>&gt; = <span class="number">1</span>...<span class="number">3</span></span><br><span class="line"><span class="keyword">let</span> range2: <span class="type">Range</span>&lt;<span class="type">Int</span>&gt; =  <span class="number">1</span>..&lt;<span class="number">3</span></span><br><span class="line"><span class="keyword">let</span> range3: <span class="type">PartialRangeThrough</span>&lt;<span class="type">Int</span>&gt; = ...<span class="number">5</span></span><br></pre></td></tr></table></figure>
<p><strong>字符、字符串也能使用区间运算符，但默认不能用在for-in中</strong></p>
<p>``` swift<br>let stringRange1 = “cc”…”ff” // ClosedRange<string><br>stringRange1.contains(“cb”) // false<br>stringRange1.contains(“dz”) // true<br>stringRange1.contains(“fg”) // false<br>let stringRange2 = “a”…”f”<br>stringRange2.contains(“d”) // true<br>stringRange2.contains(“h”) // false<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">``` swift<span class="comment">// \0到~囊括了所有可能要用到的ASCII字符</span></span><br><span class="line"><span class="keyword">let</span> characterRange: <span class="type">ClosedRange</span>&lt;<span class="type">Character</span>&gt; = <span class="string">"\0"</span>...<span class="string">"~"</span> characterRange.<span class="built_in">contains</span>(<span class="string">"G"</span>) <span class="comment">// true</span></span><br></pre></td></tr></table></figure></string></p>
<h4 id="带间隔的区间值"><a href="#带间隔的区间值" class="headerlink" title="带间隔的区间值"></a>带间隔的区间值</h4><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> hours = <span class="number">11</span></span><br><span class="line"><span class="keyword">let</span> hourInterval = <span class="number">2</span></span><br><span class="line"><span class="comment">// tickMark的取值:从4开始，累加2，不超过11</span></span><br><span class="line"><span class="keyword">for</span> tickMark <span class="keyword">in</span> <span class="built_in">stride</span>(from: <span class="number">4</span>, through: hours, by: hourInterval) &#123;</span><br><span class="line">    <span class="built_in">print</span>(tickMark)</span><br><span class="line">&#125; <span class="comment">// 4 6 8 10</span></span><br></pre></td></tr></table></figure>
<h3 id="switch"><a href="#switch" class="headerlink" title="switch"></a>switch</h3><ul>
<li>case、default后面不能写大括号{}</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> number = <span class="number">1</span></span><br><span class="line"><span class="keyword">switch</span> number &#123;</span><br><span class="line"><span class="keyword">case</span> <span class="number">1</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"number is 1"</span>)</span><br><span class="line"><span class="keyword">break</span> <span class="keyword">case</span> <span class="number">2</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"number is 2"</span>)</span><br><span class="line">    <span class="keyword">break</span></span><br><span class="line"><span class="keyword">default</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"number is other"</span>)</span><br><span class="line"><span class="keyword">break</span></span><br><span class="line">&#125; <span class="comment">// number is 1</span></span><br></pre></td></tr></table></figure>
<ul>
<li>默认可以不写break，并不会贯穿到后面的条件</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> number = <span class="number">1</span></span><br><span class="line"><span class="keyword">switch</span> number &#123;</span><br><span class="line"><span class="keyword">case</span> <span class="number">1</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"number is 1"</span>)</span><br><span class="line"><span class="keyword">case</span> <span class="number">2</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"number is 2"</span>)</span><br><span class="line"><span class="keyword">default</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"number is other"</span>)</span><br><span class="line">&#125; <span class="comment">// number is 1</span></span><br></pre></td></tr></table></figure>
<ul>
<li>使用fallthrough可以实现贯穿效果</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> number = <span class="number">1</span></span><br><span class="line"><span class="keyword">switch</span> number &#123;</span><br><span class="line"><span class="keyword">case</span> <span class="number">1</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"number is 1"</span>)</span><br><span class="line">    <span class="keyword">fallthrough</span></span><br><span class="line"><span class="keyword">case</span> <span class="number">2</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"number is 2"</span>)</span><br><span class="line"><span class="keyword">default</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"number is other"</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// number is 1</span></span><br><span class="line"><span class="comment">// number is 2</span></span><br></pre></td></tr></table></figure>
<ul>
<li>switch必须要保证能处理所有情况</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 错误示范，编译器会报错；应该加上default</span></span><br><span class="line"><span class="keyword">var</span> number = <span class="number">1</span></span><br><span class="line"><span class="keyword">switch</span> number &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">1</span>:</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">"number is 1"</span>)</span><br><span class="line">    <span class="keyword">case</span> <span class="number">2</span>:</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">"number is 2"</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>case、default后面至少要有一条语句</li>
<li>如果不想做任何事，加个break即可</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> number = <span class="number">1</span></span><br><span class="line"><span class="keyword">switch</span> number &#123;</span><br><span class="line"><span class="keyword">case</span> <span class="number">1</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"number is 1"</span>)</span><br><span class="line"><span class="keyword">case</span> <span class="number">2</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"number is 2"</span>)</span><br><span class="line"><span class="keyword">default</span>:</span><br><span class="line"><span class="keyword">break</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>如果能保证已处理所有情况，也可以不必使用default</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">enum Answer &#123; case right, wrong &#125; </span><br><span class="line">let answer = Answer.right</span><br><span class="line">switch answer &#123;</span><br><span class="line">case Answer.right:</span><br><span class="line">    print(&quot;right&quot;) </span><br><span class="line">case Answer.wrong: </span><br><span class="line">    print(&quot;wrong&quot;)</span><br><span class="line">&#125;</span><br><span class="line">// 由于已确定answer是Ansewer类型，因此可以省略Answer </span><br><span class="line">switch answer &#123;</span><br><span class="line">case .right:</span><br><span class="line">    print(&quot;right&quot;) </span><br><span class="line">case .wrong:</span><br><span class="line">    print(&quot;wrong&quot;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>switch也支持Character、String类型</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> string = <span class="string">"Jack"</span></span><br><span class="line"><span class="keyword">switch</span> string &#123;</span><br><span class="line"><span class="keyword">case</span> <span class="string">"Jack"</span>:</span><br><span class="line">    <span class="keyword">fallthrough</span></span><br><span class="line"><span class="keyword">case</span> <span class="string">"Rose"</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"Right person"</span>)</span><br><span class="line"><span class="keyword">default</span>:</span><br><span class="line">    <span class="keyword">break</span></span><br><span class="line">&#125; </span><br><span class="line"><span class="comment">// Right person</span></span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> character: <span class="type">Character</span> = <span class="string">"a"</span></span><br><span class="line"><span class="keyword">switch</span> character &#123;</span><br><span class="line"><span class="keyword">case</span> <span class="string">"a"</span>, <span class="string">"A"</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"The letter A"</span>)</span><br><span class="line"><span class="keyword">default</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"Not the letter A"</span>)</span><br><span class="line">&#125; </span><br><span class="line"><span class="comment">// The letter A</span></span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">switch</span> string &#123;</span><br><span class="line"><span class="keyword">case</span> <span class="string">"Jack"</span>, <span class="string">"Rose"</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"Right person"</span>)</span><br><span class="line"><span class="keyword">default</span>:</span><br><span class="line">    <span class="keyword">break</span></span><br><span class="line">&#125; </span><br><span class="line"><span class="comment">// Right person</span></span><br></pre></td></tr></table></figure>
<ul>
<li>区间匹配、元组匹配</li>
<li>可以使用下划线 _ 忽略某个值</li>
<li>关于case匹配问题，属于模式匹配(Pattern Matching)的范畴，以后会再次详细展开讲解</li>
</ul>
<p>``` swift<br>let count = 62<br>switch count {<br>case 0:<br>    print(“none”)<br>case 1..<5: print("a few") case 5..<12: print("several") 12..<100: print("dozens of") 100..<1000: print("hundreds default: print("many") } dozens of <figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">``` swift</span><br><span class="line">let <span class="built_in">point</span> = (<span class="number">1</span>, <span class="number">1</span>)</span><br><span class="line"><span class="built_in">switch</span> <span class="built_in">point</span> &#123;</span><br><span class="line"><span class="built_in">case</span> (<span class="number">0</span>, <span class="number">0</span>):</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"the origin"</span>)</span><br><span class="line"><span class="built_in">case</span> (_, <span class="number">0</span>):</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"on the x-axis"</span>) </span><br><span class="line"><span class="built_in">case</span> (<span class="number">0</span>, _):</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"on the y-axis"</span>) </span><br><span class="line"><span class="built_in">case</span> (<span class="number">-2.</span>.<span class="number">.2</span>, <span class="number">-2.</span>.<span class="number">.2</span>):</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"inside the box"</span>)</span><br><span class="line"><span class="built_in">default</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"outside of the box"</span>) &#125; </span><br><span class="line"><span class="comment">// inside the box</span></span><br></pre></td></tr></table></5:></p>
<ul>
<li>值绑定 必要时let也可以改为var</li>
</ul>
<p>``` swift<br>let point = (2, 0)<br>switch point {<br>case (let x, 0):<br>    print(“on the x-axis with an x value of (x)”)<br>case (0, let y):<br>    print(“on the y-axis with a y value of (y)”)<br>case let (x, y):<br>    print(“somewhere else at ((x), (y))”) } </p>
<p>// on the x-axis with an x value of 2<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">* <span class="keyword">where</span></span><br><span class="line"></span><br><span class="line">``` swift<span class="keyword">let</span> point = (<span class="number">1</span>, -<span class="number">1</span>)</span><br><span class="line"><span class="keyword">switch</span> point &#123;</span><br><span class="line"><span class="keyword">case</span> <span class="keyword">let</span> (x, y) <span class="keyword">where</span> x == y:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"on the line x == y"</span>) </span><br><span class="line"><span class="keyword">case</span> <span class="keyword">let</span> (x, y) <span class="keyword">where</span> x == -y:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"on the line x == -y"</span>) </span><br><span class="line"><span class="keyword">case</span> <span class="keyword">let</span> (x, y):</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"(\(x), \(y)) is just some arbitrary point"</span>) &#125; </span><br><span class="line"></span><br><span class="line"><span class="comment">// on the line x == -y</span></span><br></pre></td></tr></table></figure></p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 将所有正数加起来</span></span><br><span class="line"><span class="keyword">var</span> numbers = [<span class="number">10</span>, <span class="number">20</span>, -<span class="number">10</span>, -<span class="number">20</span>, <span class="number">30</span>, -<span class="number">30</span>]</span><br><span class="line"><span class="keyword">var</span> sum = <span class="number">0</span></span><br><span class="line"><span class="keyword">for</span> num <span class="keyword">in</span> numbers <span class="keyword">where</span> num &gt; <span class="number">0</span> &#123; <span class="comment">// 使用where来过滤num</span></span><br><span class="line">    sum += num </span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">print</span>(sum) <span class="comment">// 60</span></span><br></pre></td></tr></table></figure>
<ul>
<li>标签语句；指定跳出的循环层级</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">outer: <span class="keyword">for</span> i <span class="keyword">in</span> <span class="number">1</span>...<span class="number">4</span> &#123; </span><br><span class="line">    <span class="keyword">for</span> k <span class="keyword">in</span> <span class="number">1</span>...<span class="number">4</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> k == <span class="number">3</span> &#123;</span><br><span class="line">            <span class="keyword">continue</span> outer</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> i == <span class="number">3</span> &#123;</span><br><span class="line">            <span class="keyword">break</span> outer </span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">"i == \(i), k == \(k)"</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="函数"><a href="#函数" class="headerlink" title="函数"></a>函数</h2><h3 id="函数的定义"><a href="#函数的定义" class="headerlink" title="函数的定义"></a>函数的定义</h3><ul>
<li>形参默认是let，也只能是let</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">pi</span><span class="params">()</span></span> -&gt; <span class="type">Double</span> &#123; </span><br><span class="line">    <span class="keyword">return</span> <span class="number">3.14</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sum</span><span class="params">(v1: Int, v2: Int)</span></span> -&gt; <span class="type">Int</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> v1 + v2</span><br><span class="line">&#125;</span><br><span class="line">sum(v1: <span class="number">10</span>, v2: <span class="number">20</span>)</span><br></pre></td></tr></table></figure>
<ul>
<li>无返回值</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sayHello</span><span class="params">()</span></span> -&gt; <span class="type">Void</span> &#123;</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"Hello"</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sayHello</span><span class="params">()</span></span> -&gt; () &#123; </span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"Hello"</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sayHello</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"Hello"</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="隐式返回-Implicit-Return"><a href="#隐式返回-Implicit-Return" class="headerlink" title="隐式返回(Implicit Return)"></a>隐式返回(Implicit Return)</h3><ul>
<li>如果整个函数体是一个单一表达式，那么函数会隐式返回这个表达式</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sum</span><span class="params">(v1: Int, v2: Int)</span></span> -&gt; <span class="type">Int</span> &#123; </span><br><span class="line">    v1 + v2</span><br><span class="line">&#125;</span><br><span class="line">sum(v1: <span class="number">10</span>, v2: <span class="number">20</span>) <span class="comment">// 30</span></span><br></pre></td></tr></table></figure>
<h3 id="返回元组-实现多返回值"><a href="#返回元组-实现多返回值" class="headerlink" title="返回元组:实现多返回值"></a>返回元组:实现多返回值</h3><p>``` swift<br>func calculate(v1: Int, v2: Int) -&gt; (sum: Int, difference: Int, average: Int) {<br>    let sum = v1 + v2<br>    return (sum, v1 - v2, sum &gt;&gt; 1)<br>}<br>let result = calculate(v1: 20, v2: 10)<br>result.sum // 30<br>result.difference // 10<br>result.average // 15<br><figure class="highlight clean"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">### 函数的文档注释</span><br><span class="line"></span><br><span class="line">[参考官方文档](https:<span class="comment">//swift.org/documentation/api-design-guidelines/)</span></span><br><span class="line">``` swift</span><br><span class="line"><span class="comment">/// 求和【概述】 </span></span><br><span class="line"><span class="comment">///</span></span><br><span class="line"><span class="comment">/// 将2个整数相加【更详细的描述】 </span></span><br><span class="line"><span class="comment">///</span></span><br><span class="line"><span class="comment">/// - Parameter v1: 第1个整数</span></span><br><span class="line"><span class="comment">/// - Parameter v2: 第2个整数</span></span><br><span class="line"><span class="comment">/// - Returns: 2个整数的和 </span></span><br><span class="line"><span class="comment">///</span></span><br><span class="line"><span class="comment">/// - Note:传入2个整数即可【批注】</span></span><br><span class="line"><span class="comment">///</span></span><br><span class="line">func sum(v1: <span class="built_in">Int</span>, v2: <span class="built_in">Int</span>) -&gt; <span class="built_in">Int</span> &#123;</span><br><span class="line">    v1 + v2 </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="参数标签-Argument-Label"><a href="#参数标签-Argument-Label" class="headerlink" title="参数标签(Argument Label)"></a>参数标签(Argument Label)</h3><p><strong>可以修改参数标签</strong><br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">goToWork</span><span class="params">(at time: String)</span></span> &#123;</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"this time is \(time)"</span>)</span><br><span class="line">&#125;</span><br><span class="line">goToWork(at: <span class="string">"08:00"</span>)</span><br><span class="line"><span class="comment">// this time is 08:00</span></span><br></pre></td></tr></table></figure></p>
<p><strong>可以使用下划线_ 省略参数标签</strong><br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sum</span><span class="params">(<span class="number">_</span> v1: Int, <span class="number">_</span> v2: Int)</span></span> -&gt; <span class="type">Int</span> &#123; </span><br><span class="line">    v1 + v2</span><br><span class="line">&#125;</span><br><span class="line">sum(<span class="number">10</span>, <span class="number">20</span>)</span><br></pre></td></tr></table></figure></p>
<h3 id="默认参数值-Default-Parameter-Value"><a href="#默认参数值-Default-Parameter-Value" class="headerlink" title="默认参数值(Default Parameter Value)"></a>默认参数值(Default Parameter Value)</h3><p><strong>参数可以有默认值</strong><br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">check</span><span class="params">(name: String = <span class="string">"nobody"</span>, age: Int, job: String = <span class="string">"none"</span>)</span></span> &#123;</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"name=\(name), age=\(age), job=\(job)"</span>)</span><br><span class="line">&#125;</span><br><span class="line">check(name: <span class="string">"Jack"</span>, age: <span class="number">20</span>, job: <span class="string">"Doctor"</span>) <span class="comment">// name=Jack, age=20, job=Doctor</span></span><br><span class="line">check(name: <span class="string">"Rose"</span>, age: <span class="number">18</span>) <span class="comment">// name=Rose, age=18, job=none</span></span><br><span class="line">check(age: <span class="number">10</span>, job: <span class="string">"Batman"</span>) <span class="comment">// name=nobody, age=10, job=Batman</span></span><br><span class="line">check(age: <span class="number">15</span>) <span class="comment">// name=nobody, age=15, job=none</span></span><br></pre></td></tr></table></figure></p>
<p><strong>C++的默认参数值有个限制:必须从右往左设置。由于Swift拥有参数标签，因此并没有此类限制<br>但是在省略参数标签时，需要特别注意，避免出错</strong><br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 这里的middle不可以省略参数标签</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">test</span><span class="params">(<span class="number">_</span> first: Int = <span class="number">10</span>, middle: Int, <span class="number">_</span> last: Int = <span class="number">30</span>)</span></span> &#123; &#125; test(middle: <span class="number">20</span>)</span><br></pre></td></tr></table></figure></p>
<h3 id="可变参数-Variadic-Parameter"><a href="#可变参数-Variadic-Parameter" class="headerlink" title="可变参数(Variadic Parameter)"></a>可变参数(Variadic Parameter)</h3><p>``` swift<br>func sum(_ numbers: Int…) -&gt; Int {<br>    var total = 0<br>    for number in numbers {<br>        total += number<br>    }<br>    return total<br>}<br>sum(10, 20, 30, 40) // 100<br><figure class="highlight cmake"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">**一个函数最多只能有<span class="number">1</span>个可变参数**</span><br><span class="line">**紧跟在可变参数后面的参数不能省略参数标签**</span><br><span class="line">``` swift</span><br><span class="line">// 参数<span class="keyword">string</span>不能省略标签</span><br><span class="line">func <span class="keyword">test</span>(_ numbers: Int..., <span class="keyword">string</span>: <span class="keyword">String</span>, _ other: <span class="keyword">String</span>) &#123; &#125;</span><br><span class="line"><span class="keyword">test</span>(<span class="number">10</span>, <span class="number">20</span>, <span class="number">30</span>, <span class="keyword">string</span>: <span class="string">"Jack"</span>, <span class="string">"Rose"</span>)</span><br></pre></td></tr></table></figure></p>
<h3 id="Swift自带的print函数"><a href="#Swift自带的print函数" class="headerlink" title="Swift自带的print函数"></a>Swift自带的print函数</h3><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/// - Parameters:</span></span><br><span class="line"><span class="comment">///     - items: Zero or more items to print.</span></span><br><span class="line"><span class="comment">///     - separator: A string to print between each item. The default is a single space (`" "`). </span></span><br><span class="line"><span class="comment">///     - terminator: The string to print after all items have been printed. The</span></span><br><span class="line"><span class="comment">///       default is a newline (`"\n"`).</span></span><br><span class="line"><span class="keyword">public</span> <span class="function"><span class="keyword">func</span> <span class="title">print</span><span class="params">(<span class="number">_</span> items: <span class="keyword">Any</span>..., separator: String = <span class="string">" "</span>, terminator: String = <span class="string">"\n"</span>)</span></span></span><br></pre></td></tr></table></figure>
<p>``` swift<br>print(1, 2, 3, 4, 5) // 1 2 3 4 5<br>print(1, 2, 3, 4, 5, separator: “_”) // 1_2_3_4_5<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">``` swift<span class="function"><span class="title">print</span><span class="params">(<span class="string">"My name is Jake."</span>, terminator: <span class="string">""</span>)</span></span> </span><br><span class="line"><span class="function"><span class="title">print</span><span class="params">(<span class="string">"My age is 18."</span>)</span></span></span><br><span class="line"><span class="comment">// My name is Jake.My age is 18.</span></span><br></pre></td></tr></table></figure></p>
<h3 id="输入输出参数-In-Out-Parameter"><a href="#输入输出参数-In-Out-Parameter" class="headerlink" title="输入输出参数(In-Out Parameter)"></a>输入输出参数(In-Out Parameter)</h3><p><strong>可以用inout定义一个输入输出参数:可以在函数内部修改外部实参的值</strong><br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">swapValues</span><span class="params">(<span class="number">_</span> v1: <span class="keyword">inout</span> Int, <span class="number">_</span> v2: <span class="keyword">inout</span> Int)</span></span> &#123; </span><br><span class="line">    <span class="keyword">let</span> tmp = v1</span><br><span class="line">    v1 = v2</span><br><span class="line">    v2 = tmp </span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> num1 = <span class="number">10</span></span><br><span class="line"><span class="keyword">var</span> num2 = <span class="number">20</span></span><br><span class="line">swapValues(&amp;num1, &amp;num2)</span><br></pre></td></tr></table></figure></p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">swapValues</span><span class="params">(<span class="number">_</span> v1: <span class="keyword">inout</span> Int, <span class="number">_</span> v2: <span class="keyword">inout</span> Int)</span></span> &#123; </span><br><span class="line">    (v1, v2) = (v2, v1)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>可变参数不能标记为inout<br>inout参数不能有默认值<br>inout参数只能传入可以被多次赋值的<br>inout参数的本质是地址传递(引用传递)</p>
</blockquote>
<h3 id="函数重载-Function-Overload"><a href="#函数重载-Function-Overload" class="headerlink" title="函数重载(Function Overload)"></a>函数重载(Function Overload)</h3><ul>
<li>规则<ul>
<li>函数名相同</li>
<li>参数个数不同 || 参数类型不同 || 参数标签不同</li>
</ul>
</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sum</span><span class="params">(v1: Int, v2: Int)</span></span> -&gt; <span class="type">Int</span> &#123; </span><br><span class="line">    v1 + v2</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sum</span><span class="params">(v1: Int, v2: Int, v3: Int)</span></span> -&gt; <span class="type">Int</span> &#123; </span><br><span class="line">    v1 + v2 + v3</span><br><span class="line">&#125; <span class="comment">// 参数个数不同</span></span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sum</span><span class="params">(v1: Double, v2: Int)</span></span> -&gt; <span class="type">Double</span> &#123;</span><br><span class="line">    v1 + <span class="type">Double</span>(v2) &#125; <span class="comment">// 参数类型不同</span></span><br><span class="line">&#125; <span class="comment">// 参数类型不同</span></span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sum</span><span class="params">(<span class="number">_</span> v1: Int, <span class="number">_</span> v2: Int)</span></span> -&gt; <span class="type">Int</span> &#123; </span><br><span class="line">    v1 + v2</span><br><span class="line">&#125; <span class="comment">// 参数标签不同</span></span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sum</span><span class="params">(a: Int, b: Int)</span></span> -&gt; <span class="type">Int</span> &#123;</span><br><span class="line">    a+b</span><br><span class="line">&#125; <span class="comment">// 参数标签不同</span></span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">sum(v1: <span class="number">10</span>, v2: <span class="number">20</span>) <span class="comment">// 30 </span></span><br><span class="line">sum(v1: <span class="number">10</span>, v2: <span class="number">20</span>, v3: <span class="number">30</span>) <span class="comment">// 60 </span></span><br><span class="line">sum(v1: <span class="number">10</span>, v2: <span class="number">20.0</span>) <span class="comment">// 30.0 </span></span><br><span class="line">sum(v1: <span class="number">10.0</span>, v2: <span class="number">20</span>) <span class="comment">// 30.0 </span></span><br><span class="line">sum(<span class="number">10</span>, <span class="number">20</span>) <span class="comment">// 30</span></span><br><span class="line">sum(a: <span class="number">10</span>, b: <span class="number">20</span>) <span class="comment">// 30</span></span><br></pre></td></tr></table></figure>
<p><strong>返回值类型与函数重载无关</strong><br><img src="https://object.renchengqi.com/blog/g2c1n.png" alt><br><strong>默认参数值和函数重载一起使用产生二义性时，编译器并不会报错(在C++中会报错)</strong><br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sum</span><span class="params">(v1: Int, v2: Int)</span></span> -&gt; <span class="type">Int</span> &#123; </span><br><span class="line">    v1 + v2</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sum</span><span class="params">(v1: Int, v2: Int, v3: Int = <span class="number">10</span>)</span></span> -&gt; <span class="type">Int</span> &#123;</span><br><span class="line">    v1 + v2 + v3 </span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 会调用sum(v1: Int, v2: Int) </span></span><br><span class="line">sum(v1: <span class="number">10</span>, v2: <span class="number">20</span>)</span><br></pre></td></tr></table></figure></p>
<p><strong>可变参数、省略参数标签、函数重载一起使用产生二义性时，编译器有可能会报错</strong><br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sum</span><span class="params">(v1: Int, v2: Int)</span></span> -&gt; <span class="type">Int</span> &#123; </span><br><span class="line">    v1 + v2</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sum</span><span class="params">(<span class="number">_</span> v1: Int, <span class="number">_</span> v2: Int)</span></span> -&gt; <span class="type">Int</span> &#123;</span><br><span class="line">    v1 + v2 </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sum</span><span class="params">(<span class="number">_</span> numbers: Int...)</span></span> -&gt; <span class="type">Int</span> &#123; <span class="keyword">var</span> total = <span class="number">0</span></span><br><span class="line">    <span class="keyword">for</span> number <span class="keyword">in</span> numbers &#123;</span><br><span class="line">        total += number</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> total</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// error: ambiguous use of 'sum'</span></span><br><span class="line">sum(<span class="number">10</span>, <span class="number">20</span>)</span><br></pre></td></tr></table></figure></p>
<h3 id="内联函数"><a href="#内联函数" class="headerlink" title="内联函数"></a>内联函数</h3><p><img src="https://object.renchengqi.com/blog/i1pnj.png" alt></p>
<ul>
<li><p>如果开启了编译器优化(Release模式默认会开启优化)，编译器会自动将某些函数变成内联函数 p将函数调用展开成函数体</p>
</li>
<li><p>哪些函数不会被自动内联? </p>
<ul>
<li>函数体比较长 </li>
<li>包含递归调用 </li>
<li>包含动态派发</li>
</ul>
</li>
</ul>
<p><strong>@inline</strong><br>``` swift<br>// 永远不会被内联(即使开启了编译器优化)<br>@inline(never) func test() {<br>    print(“test”)<br>}<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">``` swift</span><br><span class="line"><span class="comment">// 开启编译器优化后，即使代码很长，也会被内联(递归调用函数、动态派发的函数除外) </span></span><br><span class="line">@inline(__always) <span class="function"><span class="keyword">func</span> <span class="title">test</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"test"</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<blockquote>
<p>在Release模式下，编译器已经开启优化，会自动决定哪些函数需要内联，因此没必要使用@inline</p>
</blockquote>
<h3 id="函数类型-Function-Type"><a href="#函数类型-Function-Type" class="headerlink" title="函数类型(Function Type)"></a>函数类型(Function Type)</h3><p><strong>每一个函数都是有类型的，函数类型由形式参数类型、返回值类型组成</strong><br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">test</span><span class="params">()</span></span> &#123; &#125; <span class="comment">// () -&gt; Void 或者 () -&gt; ()</span></span><br></pre></td></tr></table></figure></p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sum</span><span class="params">(a: Int, b: Int)</span></span> -&gt; <span class="type">Int</span> &#123; </span><br><span class="line">    a+b</span><br><span class="line">&#125; <span class="comment">// (Int, Int) -&gt; Int</span></span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 定义变量</span></span><br><span class="line"><span class="keyword">var</span> fn: (<span class="type">Int</span>, <span class="type">Int</span>) -&gt; <span class="type">Int</span> = sum </span><br><span class="line">fn(<span class="number">2</span>, <span class="number">3</span>) <span class="comment">// 5，调用时不需要参数标签</span></span><br></pre></td></tr></table></figure>
<p><strong>函数类型作为函数参数</strong><br>``` swift<br>func sum(v1: Int, v2: Int) -&gt; Int {<br>    v1 + v2<br>}<br>func difference(v1: Int, v2: Int) -&gt; Int {<br>    v1 - v2<br>}<br>func printResult(_ mathFn: (Int, Int) -&gt; Int, _ a: Int, _ b: Int) {<br>    print(“Result: (mathFn(a, b))”)<br>}<br>printResult(sum, 5, 2) // Result: 7<br>printResult(difference, 5, 2) // Result: 3<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">**函数类型作为函数返回值**</span><br><span class="line">``` swift</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">next</span><span class="params">(<span class="number">_</span> input: Int)</span></span> -&gt; <span class="type">Int</span> &#123; </span><br><span class="line">    input + <span class="number">1</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">previous</span><span class="params">(<span class="number">_</span> input: Int)</span></span> -&gt; <span class="type">Int</span> &#123;</span><br><span class="line">    input - <span class="number">1</span> </span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">forward</span><span class="params">(<span class="number">_</span> forward: Bool)</span></span> -&gt; (<span class="type">Int</span>) -&gt; <span class="type">Int</span> &#123; </span><br><span class="line">    forward ? next : previous</span><br><span class="line">&#125;</span><br><span class="line">forward(<span class="literal">true</span>)(<span class="number">3</span>) <span class="comment">// 4</span></span><br><span class="line">forward(<span class="literal">false</span>)(<span class="number">3</span>) <span class="comment">// 2</span></span><br></pre></td></tr></table></figure></p>
<blockquote>
<p>返回值是函数类型的函数，叫做高阶函数(Higher-Order Function)</p>
</blockquote>
<h3 id="函数别名（typealias）"><a href="#函数别名（typealias）" class="headerlink" title="函数别名（typealias）"></a>函数别名（typealias）</h3><p><strong>typealias用来给类型起别名</strong><br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typealias</span> <span class="type">Byte</span> = <span class="type">Int8</span></span><br><span class="line"><span class="keyword">typealias</span> <span class="type">Short</span> = <span class="type">Int16</span></span><br><span class="line"><span class="keyword">typealias</span> <span class="type">Long</span> = <span class="type">Int64</span></span><br></pre></td></tr></table></figure></p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typealias</span> <span class="type">Date</span> = (year: <span class="type">Int</span>, month: <span class="type">Int</span>, day: <span class="type">Int</span>) <span class="function"><span class="keyword">func</span> <span class="title">test</span><span class="params">(<span class="number">_</span> date: Date)</span></span> &#123;</span><br><span class="line">    <span class="built_in">print</span>(date.<span class="number">0</span>)</span><br><span class="line">    <span class="built_in">print</span>(date.year) </span><br><span class="line">&#125;</span><br><span class="line">test((<span class="number">2011</span>, <span class="number">9</span>, <span class="number">10</span>))</span><br></pre></td></tr></table></figure>
<p><strong>按照Swift标准库的定义，Void就是空元组()</strong><br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">typealias</span> <span class="type">Void</span> = ()</span><br><span class="line"></span><br><span class="line"><span class="keyword">typealias</span> <span class="type">IntFn</span> = (<span class="type">Int</span>, <span class="type">Int</span>) -&gt; <span class="type">Int</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">difference</span><span class="params">(v1: Int, v2: Int)</span></span> -&gt; <span class="type">Int</span> &#123; </span><br><span class="line">    v1 - v2</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> fn: <span class="type">IntFn</span> = difference</span><br><span class="line">fn(<span class="number">20</span>, <span class="number">10</span>) <span class="comment">// 10</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">setFn</span><span class="params">(<span class="number">_</span> fn: IntFn)</span></span> &#123; &#125; setFn(difference)</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">getFn</span><span class="params">()</span></span> -&gt; <span class="type">IntFn</span> &#123; </span><br><span class="line">    difference </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>

      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/iOS/" rel="tag"># iOS</a>
          
            <a href="/tags/Swift/" rel="tag"># Swift</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/07/14/python/网络编程03/" rel="next" title="Python-网络编程（二）">
                <i class="fa fa-chevron-left"></i> Python-网络编程（二）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/07/24/ios/general/iOS13和Xcode11踩坑/" rel="prev" title="iOS13和Xcode11踩坑">
                iOS13和Xcode11踩坑 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.JPG" alt="任成">
            
              <p class="site-author-name" itemprop="name">任成</p>
              <div class="site-description motion-element" itemprop="description"></div>
          </div>

          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0NvZGVyQ3VydmU=" title="GitHub &rarr; https://github.com/CoderCurve"><i class="fa fa-fw fa-github"></i>GitHub</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="bWFpbHRvOnJlbmNoZW5nMTFAaWNsb3VkLmNvbQ==" title="E-Mail &rarr; mailto:rencheng11@icloud.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</span>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#基础语法"><span class="nav-number">1.</span> <span class="nav-text">基础语法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#输出"><span class="nav-number">1.1.</span> <span class="nav-text">输出</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#注释"><span class="nav-number">1.2.</span> <span class="nav-text">注释</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#常量"><span class="nav-number">1.3.</span> <span class="nav-text">常量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#标识符"><span class="nav-number">1.4.</span> <span class="nav-text">标识符</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#常用数据类型"><span class="nav-number">1.5.</span> <span class="nav-text">常用数据类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#字面量"><span class="nav-number">1.6.</span> <span class="nav-text">字面量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#类型转换"><span class="nav-number">1.7.</span> <span class="nav-text">类型转换</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#元组"><span class="nav-number">1.8.</span> <span class="nav-text">元组</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#流程控制"><span class="nav-number">2.</span> <span class="nav-text">流程控制</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#if-else"><span class="nav-number">2.1.</span> <span class="nav-text">if-else</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#while"><span class="nav-number">2.2.</span> <span class="nav-text">while</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#for"><span class="nav-number">2.3.</span> <span class="nav-text">for</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#闭区间运算符：a…b-a-lt-取值-lt-b"><span class="nav-number">2.3.1.</span> <span class="nav-text">闭区间运算符：a…b, a &lt;= 取值 &lt;= b</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#半开区间运算符：a-lt-b-a-lt-取值-lt-b"><span class="nav-number">2.3.2.</span> <span class="nav-text">半开区间运算符：a..&lt;b, a &lt;= 取值 &lt; b</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#区间运算符用在数组上"><span class="nav-number">2.3.3.</span> <span class="nav-text">区间运算符用在数组上</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#区间类型"><span class="nav-number">2.3.4.</span> <span class="nav-text">区间类型</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#带间隔的区间值"><span class="nav-number">2.3.5.</span> <span class="nav-text">带间隔的区间值</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#switch"><span class="nav-number">2.4.</span> <span class="nav-text">switch</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#函数"><span class="nav-number">3.</span> <span class="nav-text">函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#函数的定义"><span class="nav-number">3.1.</span> <span class="nav-text">函数的定义</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#隐式返回-Implicit-Return"><span class="nav-number">3.2.</span> <span class="nav-text">隐式返回(Implicit Return)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#返回元组-实现多返回值"><span class="nav-number">3.3.</span> <span class="nav-text">返回元组:实现多返回值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参数标签-Argument-Label"><span class="nav-number">3.4.</span> <span class="nav-text">参数标签(Argument Label)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#默认参数值-Default-Parameter-Value"><span class="nav-number">3.5.</span> <span class="nav-text">默认参数值(Default Parameter Value)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#可变参数-Variadic-Parameter"><span class="nav-number">3.6.</span> <span class="nav-text">可变参数(Variadic Parameter)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Swift自带的print函数"><span class="nav-number">3.7.</span> <span class="nav-text">Swift自带的print函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#输入输出参数-In-Out-Parameter"><span class="nav-number">3.8.</span> <span class="nav-text">输入输出参数(In-Out Parameter)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#函数重载-Function-Overload"><span class="nav-number">3.9.</span> <span class="nav-text">函数重载(Function Overload)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#内联函数"><span class="nav-number">3.10.</span> <span class="nav-text">内联函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#函数类型-Function-Type"><span class="nav-number">3.11.</span> <span class="nav-text">函数类型(Function Type)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#函数别名（typealias）"><span class="nav-number">3.12.</span> <span class="nav-text">函数别名（typealias）</span></a></li></ol></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">  <span class="exturl" data-url="aHR0cDovL3d3dy5iZWlhbi5taWl0Lmdvdi5jbg==">京ICP备18001214号 </span>&copy; 2014 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">任成</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
    <span title="站点总字数">277k</span>
  

  
</div>









        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/utils.js?v=7.1.2"></script>

  <script src="/js/motion.js?v=7.1.2"></script>



  
  


  <script src="/js/affix.js?v=7.1.2"></script>

  <script src="/js/schemes/pisces.js?v=7.1.2"></script>



  
  <script src="/js/scrollspy.js?v=7.1.2"></script>
<script src="/js/post-details.js?v=7.1.2"></script>



  


  <script src="/js/next-boot.js?v=7.1.2"></script>


  

  
  <script src="/js/exturl.js?v=7.1.2"></script>


  

  


  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
  

  
  

  


  

  
<script>
if ($('body').find('pre.mermaid').length) {
  $.ajax({
    type: 'GET',
    url: '//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js',
    dataType: 'script',
    cache: true,
    success: function() {
      mermaid.initialize({
        theme: 'forest',
        logLevel: 3,
        flowchart: { curve: 'linear' },
        gantt: { axisFormat: '%m/%d/%Y' },
        sequence: { actorMargin: 50 }
      });
    }
  });
}
</script>


  

  

  

  

  

  

  

  

  

</body>
</html>
